package com.iwhalecloud.bss.kite.cucc.service.custview;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import javax.annotation.Resource;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.service.custview.evolve.task.*;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceBus;
import com.iwhalecloud.bss.kite.cucc.service.order.ContractService;
import com.iwhalecloud.bss.kite.cucc.service.util.CallClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.callclient.service.IOrderQueryService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.entity.InfService;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.custview.ICustViewService;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IAttachmentService;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.dto.custview.MemUserQueryReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.UserQueryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosCustomerDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.webService.AccessoryInfoRsp;
import com.iwhalecloud.bss.kite.cucc.client.dto.webService.CustContractRsp;
import com.iwhalecloud.bss.kite.cucc.client.enumerate.UserDetailTagName;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewVO;
import com.iwhalecloud.bss.kite.cucc.common.callclient.constant.CallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.callclient.service.ICuccQueryInfService;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.WebServiceUtil;
import com.iwhalecloud.bss.kite.cucc.service.custview.evolve.CustViewCallable;
import com.iwhalecloud.bss.kite.cucc.service.custview.evolve.CustViewCallableBuilder;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.common.util.FunctionWrapper;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.cucc.service.util.webService.WebServiceHelper;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;

import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.log.ZSmartLogger;

/**
 * @ClassName : CustViewService
 * @Description : 集团客户/成员订购信息查询
 * @Author : xie.zhengjun
 * @Date : 2021/1/11 16:01
 */
@Service("custViewService")
public class CustViewService implements ICustViewService {
    @Resource
    private IOrderService orderService;

    @Resource
    private IInfServiceBus infServiceBus;

    @Autowired
    ContractService contractService;

    @Resource
    private IAttachmentService attachmentService;

    private final ZSmartLogger logger = ZSmartLogger.getLogger(CustViewService.class);

    @Value("${interface.call.mode:hsf}")
    private String mode;

    @Override
    public UserQueryDTO queryUserList(MemUserQueryReq memUserQueryReq) {
        UserQueryDTO userQueryDTO = new UserQueryDTO();
        // 按集团客户查询
        if (KiteStringUtils.isEqual(memUserQueryReq.getQueryMode(), "0")) {
            Map<String, String> map = new HashMap<>();
            map.put("accNum", memUserQueryReq.getGrpUserNum());
            map.put("userName", memUserQueryReq.getGrpUserName());
            map.put("eparchyCode", memUserQueryReq.getCityCode());
            map.put("provinceCode", memUserQueryReq.getProvinceCode());
            userQueryDTO = infServiceBus.queryUserList(map);
        }

        return userQueryDTO;
    }

    @Override
    public CustViewVO getCustView(String accNum, String userState) {
        CustViewVO custViewVO = new CustViewVO();
        StopWatch stopWatch = new StopWatch("getCustView");
        stopWatch.start("查询接口");
        KitePosDTO kitePosDTO = null;
        Map<String, Object> userDetail = null;

        String staffCode = ContextUtil.getLoginInfo().getStaffInfo().getStaffCode();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        String eparchyCode = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        String inDepartName = "";

        //是否是销户用户
        boolean isInvalid = KiteStringUtils.equals(userState, "40");

        try {
            //查询用户详情
            Map<String, Object> inMap = new HashMap<>();
            inMap.put("accNum", accNum);
            inMap.put("staffCode", staffCode);
            inMap.put("eparchyCode", eparchyCode);
            inMap.put("provinceCode", provinceCode);
            //IInfServiceBus infServiceBus = SpringUtil.getBean(IInfServiceBus.class);
            userDetail = this.queryUserDetail(inMap, Lists.newArrayList(
                UserDetailTagName.USER, UserDetailTagName.USER_ITEM,
                UserDetailTagName.PAYRELATION, UserDetailTagName.USER_DISCNT,
                UserDetailTagName.USER_DISCNT_ITEM, UserDetailTagName.USER_CONTRACT,
                UserDetailTagName.USER_AGNET, UserDetailTagName.USER_DEVELOP,
                UserDetailTagName.USER_CONTACT, UserDetailTagName.USER_GOODS,
                UserDetailTagName.USER_RELATION, UserDetailTagName.USER_RELATION_ITEM,
                UserDetailTagName.USER_RELATION_P), isInvalid);

            //查询变更信息
            Map<String, Object> orderInfo = this.getChangeOriginOrder(null, null, accNum, isInvalid, null);
            kitePosDTO = JSONObject.toJavaObject(JSON.parseObject(JSON.toJSONString(orderInfo)), KitePosDTO.class);
            KitePosCustomerDTO customer = kitePosDTO.getCustomer();
            Map<String, Object> customerMap = (Map<String, Object>) orderInfo.get("customer");
            if (KiteMapUtils.isNotEmpty(customerMap)) {
                String eparchyCity = KiteMapUtils.getString(customerMap, "eparchyCode");
                customer.setEparchyCity(eparchyCity);
            }
            kitePosDTO.setCustomer(customer);

            Map<String, Object> userInfo = (Map<String, Object>) userDetail.get("USER_INFO");
            String inDepartId = KiteMapUtils.getString(userInfo, "IN_DEPART_ID");
            inDepartName = this.translateInDepart(inDepartId);
        } catch (BssException e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut(e, "获取用户信息失败");
        }
        stopWatch.stop();

        stopWatch.start("执行多线程任务");
        List<CustViewCallable> custViewCallables = getCustViewCallables(accNum, custViewVO, kitePosDTO, userDetail,
            provinceCode, inDepartName);
        ExecutorService executorService = null;
        try {
            executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1,
                Runtime.getRuntime().availableProcessors() + 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10),
                new ThreadFactoryBuilder().setNameFormat("cust-view-pool-%d").build());
            executorService.invokeAll(custViewCallables);
        } catch (InterruptedException e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut(e, "集团客户订购信息查询失败");
        } finally {
            if (Objects.nonNull(executorService)) {
                executorService.shutdown();
            }
        }
        stopWatch.stop();
        logger.info(stopWatch.prettyPrint());

        return custViewVO;
    }

    @Override
    public CustViewVO getCustViewEvolve(String accNum, String userState,String provinceCode,String eparchyCode, String userId) {
        CustViewVO custViewVO = new CustViewVO();
        StopWatch stopWatch = new StopWatch("getCustViewEvolve");
        stopWatch.start("查询接口");

        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        String staffCode = loginInfo.getStaffInfo().getStaffCode();
        if (KiteStringUtils.isEmpty(provinceCode)) {
            provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        }
        if (KiteStringUtils.isEmpty(eparchyCode)) {
            eparchyCode = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        }
        //是否是销户用户
        boolean isInvalid = KiteStringUtils.equals(userState, "40");

        Map<String, Object> inMap = new HashMap<>();
        inMap.put("userId", userId);
        inMap.put("accNum", accNum);
        inMap.put("staffCode", staffCode);
        inMap.put("eparchyCode", eparchyCode);
        inMap.put("provinceCode", provinceCode);

        //查询用户详情
        CompletableFuture<Map<String, Object>> userDetailFuture = CompletableFuture.supplyAsync(FunctionWrapper
            .wrapLoginInfo((Supplier<Map<String, Object>>) () -> queryUserDetail(inMap, Lists
                .newArrayList(UserDetailTagName.USER, UserDetailTagName.USER_ITEM, UserDetailTagName.PAYRELATION,
                    UserDetailTagName.USER_DISCNT, UserDetailTagName.USER_DISCNT_ITEM, UserDetailTagName.USER_CONTRACT,
                    UserDetailTagName.USER_AGNET, UserDetailTagName.USER_DEVELOP, UserDetailTagName.USER_CONTACT,
                    UserDetailTagName.USER_GOODS, UserDetailTagName.USER_RELATION, UserDetailTagName.USER_RELATION_P,
                    UserDetailTagName.USER_RELATION_ITEM, UserDetailTagName.USER_SVC_STATE), isInvalid)));
        // 查询变更单详情接口
        CompletableFuture<Map<String, Object>> orderInfoFuture = CompletableFuture.supplyAsync(FunctionWrapper
            .wrapLoginInfo((Supplier<Map<String, Object>>) () -> getChangeOriginOrder(null, null, accNum, isInvalid, userId)));

        Map<String, Object> userDetail = userDetailFuture.join();
        Map<String, Object> orderInfo = orderInfoFuture.join();
        if (KiteMapUtils.isEmpty(userDetail) || KiteMapUtils.isEmpty(orderInfo)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("集团客户订购信息查询失败");
        }

        KitePosDTO kitePosDTO = JSONObject.toJavaObject(JSON.parseObject(JSON.toJSONString(orderInfo)), KitePosDTO.class);
        KitePosCustomerDTO customer = kitePosDTO.getCustomer();
        Map<String, Object> customerMap = (Map<String, Object>) orderInfo.get("customer");
        if (KiteMapUtils.isNotEmpty(customerMap)) {
            String eparchyCity = KiteMapUtils.getString(customerMap, "eparchyCode");
            customer.setEparchyCity(eparchyCity);
        }

        Map<String, Object> userInfo = (Map<String, Object>) userDetail.get("USER_INFO");
        String inDepartId = KiteMapUtils.getString(userInfo, "IN_DEPART_ID");
        String inDepartName = this.translateInDepart(inDepartId);
        stopWatch.stop();

        stopWatch.start("执行多线程任务");
        List<CustViewCallable> custViewCallables = getCustViewCallables(accNum, custViewVO, kitePosDTO, userDetail,
            provinceCode, inDepartName);
        ExecutorService executorService = null;
        try {
            executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1,
                Runtime.getRuntime().availableProcessors() + 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10),
                new ThreadFactoryBuilder().setNameFormat("cust-view-pool-%d").build());
            executorService.invokeAll(custViewCallables);
        } catch (InterruptedException e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut(e, "集团客户订购信息查询失败");
        } finally {
            if (Objects.nonNull(executorService)) {
                executorService.shutdown();
            }
        }
        stopWatch.stop();
        logger.info(stopWatch.prettyPrint());
        return custViewVO;
    }

    private List<CustViewCallable> getCustViewCallables(String accNum, CustViewVO custViewVO,
        KitePosDTO kitePosDTO, Map<String, Object> userDetail, String provinceCode, String inDepartName) {
        return Lists.newArrayList(new CustViewCallableBuilder().setCustViewTask(new GroupCustInfoTask())
                .setArgs(new Object[] {kitePosDTO, custViewVO, "0"}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new UserInfoTask())
                .setArgs(new Object[] {userDetail, custViewVO, inDepartName}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new ProductInfoTask())
                .setArgs(new Object[] {kitePosDTO, custViewVO, userDetail}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new PayRelationTask())
                .setArgs(new Object[] {accNum, userDetail, custViewVO}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new FeeInfoTask())
                .setArgs(new Object[] {userDetail, custViewVO}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new GroupInfoTask())
                .setArgs(new Object[] {userDetail, custViewVO, accNum}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new CommonInfoTask())
                .setArgs(new Object[] {userDetail, custViewVO, provinceCode}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new RentInfoTask())
                .setArgs(new Object[] {userDetail, custViewVO}).withSession().build(),
            new CustViewCallableBuilder().setCustViewTask(new RelationInfoTask())
                .setArgs(new Object[] {userDetail, custViewVO}).withSession().build());
    }

    @Override
    public CustContractRsp getContractInfo(String custId, String provinceCode, String contractId,String goodId,String contractType) {
        String code= DcPublicCache.getPCode("20211224001","ZWY");
        List<CustContractRsp> custContractRsps = new ArrayList<>();
        CustContractRsp contractRsp = null;
        if(KiteStringUtils.isNotEmpty(goodId)&&KiteStringUtils.isNotEmpty(goodId)&&KiteStringUtils.contains(code,goodId)){
            IOrderQueryService orderQueryService = SpringUtil.getBean(IOrderQueryService.class);
            InfService infService = orderQueryService.queryServiceBySvcCode(
                LocalCallClientEnum.QRY_CONTRACT_INFO.getServiceCode(),
                LocalCallClientEnum.QRY_CONTRACT_INFO.getCenterCode());

            String reqString = WebServiceHelper.replaceContractReq(
                provinceCode, null, custId, contractId, null, null, null);
            try {
                // "http://10.124.150.230:8000/services/QryContractForOrderSer/v1?wsdl"
                custContractRsps = WebServiceHelper.dealContractResp(WebServiceUtil
                    .invoke(reqString, SpringUtil.getBean(ICuccQueryInfService.class).getUrlByType(infService)));
            } catch (Exception e) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut(e, "查询合同出错");
            }
            if (KiteListUtils.isNotEmpty(custContractRsps)) {
                contractRsp = custContractRsps.get(0);

                //翻译合同状态
                String statusCode = Optional.ofNullable(AttrValueCache.getAttrValue(
                    "202103220000", contractRsp.getStatusCode())
                ).map(AttrValue::getAttrValueName).orElse(contractRsp.getStatusCode());
                contractRsp.setStatusCode(statusCode);
                //合同附件
                AccessoryInfoRsp accessoryInfoRsp = new AccessoryInfoRsp();
                String accessoryId = contractRsp.getAccessoryId();
                if (KiteStringUtils.isNotEmpty(accessoryId)) {
                    //获取文件名
                    String[] split = accessoryId.split("/");
                    String fileName = split[split.length - 1];
                    if (fileName.contains("*")) {
                        String[] split1 = fileName.split("\\*");
                        accessoryId = split[0] + "/" + split[1] + "/" + split1[0];
                        fileName = split1[2];
                    }
                    //获取附件连接
                    String attachView = attachmentService.attachView(accessoryId, fileName, false);
                    accessoryInfoRsp.setLocaltionUrl(attachView);
                    accessoryInfoRsp.setOriginalName(fileName);
                }
                contractRsp.setAccessoryInfo(Collections.singletonList(accessoryInfoRsp));
            }
        }else{
            Map<String, Object> contractInfoMap = infServiceBus.listContractInfos(custId, null, null,
                contractType, provinceCode, 1, 10,contractId);
            custContractRsps= InfServiceBus.dealContractResp((List<Map<String, Object>>) contractInfoMap.get("list"));
            contractRsp = custContractRsps.get(0);
        }
        return contractRsp;
    }

    /**
     * 查询用户详情
     *
     * @param inMap
     * @param userDetailTagNames TAG_NAME 详情见{@link UserDetailTagName}
     * @return
     */
    public Map<String, Object> queryUserDetail(Map<String, Object> inMap, List<UserDetailTagName> userDetailTagNames
        , boolean isInvalid) {
        if (KiteListUtils.isEmpty(userDetailTagNames)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("TAG_NAME不可为空");
        }
        String provinceCode = KiteMapUtils.getString(inMap, "provinceCode");
        String eparchyCode = KiteMapUtils.getString(inMap, "eparchyCode");
        String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
        String accNum = KiteMapUtils.getString(inMap, "accNum");
        String userId = KiteMapUtils.getString(inMap, "userId");

        Map<String, Object> uniBssBodyMap = new HashMap<String, Object>();
        Map<String, Object> reqMap = new HashMap<String, Object>();
        //tcp_cont
        Map<String, String> tcpContMap = new HashMap<String, String>();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        reqMap.put("TCP_CONT", tcpContMap);
        // 省份编码(适配老销售)只查用户中心可不传递
//        reqMap.put("PROVINCE_CODE", provinceCode);
        // 地市编码(适配老销售)只查用户中心可不传递，只查用户中心
        // reqMap.put("EPARCHY_CODE", eparchyCode);
        // 员工工号（适配老销售）只查用户中心可不传递
        reqMap.put("STAFF_CODE", staffCode);
        // 服务号码（业务号码、用户标识二选一必填）
        reqMap.put("SERIAL_NUMBER", accNum);
        // 用户标识（业务号码、用户标识二选一必填）
        reqMap.put("USER_ID", userId);
        // 只查询用户中心
        reqMap.put("USER_SOURCE", "2");
        List<Map<String, String>> qryTagInfoList = new ArrayList<>();
        for (UserDetailTagName userDetailTagName : userDetailTagNames) {
            Map<String, String> qryTagInfo = new HashMap<>();
            qryTagInfo.put("TRANSLATE_FLAG", "1");
            qryTagInfo.put("VALID_FLAG", "1");
            qryTagInfo.put("TAG_NAME", userDetailTagName.name());
            if (KiteStringUtils.equalsAny(userDetailTagName.name(),
                UserDetailTagName.USER.name(),
                UserDetailTagName.USER_DISCNT.name(),
                UserDetailTagName.USER_DISCNT_ITEM.name(),
                UserDetailTagName.USER_SVC_STATE.name())) {
                qryTagInfo.put("VALID_FLAG", "0");
            }
            if (isInvalid) {
                qryTagInfo.put("VALID_FLAG", "0");
            }
            qryTagInfoList.add(qryTagInfo);
        }
        reqMap.put("QRY_TAG_INFOS", qryTagInfoList);
        uniBssBodyMap.put("REQ", reqMap);
        Map<String, Object> requestMap = LocalTokenUtil.getParamMap(uniBssBodyMap);
        requestMap.put("OP_CODE", "json_bbssUserCenter_QryUserDetailServiceApi_qryUserDetailInfo");
        InfServiceHelper.adaptGray(requestMap, reqMap);

        //调接口查询用户详情信息
        Map rsp;
        if (KiteStringUtils.isEqual(mode, "http")) {
            rsp = HttpsCallClient.postObjMap(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), requestMap, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            String resultStr = infExchangeService.exchange(new JSONObject(requestMap));
            rsp = JSON.parseObject(resultStr, Map.class);
        }

        Map<String, Object> uniBssHead = (Map<String, Object>) rsp.get("UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(LocalInfConsts.RESP_SUCCESS, KiteMapUtils.getString(uniBssHead, "RESP_CODE"))) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> rspUniBssBodyMap = (Map<String, Object>) rsp.get("UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(rspUniBssBodyMap)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("接口返回报文缺少UNI_BSS_BODY节点信息!");
        }

        Map<String, Object> rspMap = (Map<String, Object>) rspUniBssBodyMap.get("RSP");
        if (!KiteStringUtils.equals("0000", KiteMapUtils.getString(rspMap, "RESP_CODE"))) {
            if (KiteStringUtils.equals("8888", KiteMapUtils.getString(rspMap, "RESP_CODE"))) {
                return null;
            }
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(rspMap, "RESP_DESC"));
        }
        return rspMap;
    }

    /***
     * 从集客获取变更信息
     * @param productId
     * @param custId
     * @param serialNumber
     * @return
     */
    public Map<String, Object> getChangeOriginOrder(String productId, String custId, String serialNumber,
                                                    boolean isInvalid, String userId) {

        Map<String, Object> param = new HashMap<>();
        Map uniBssBody = new HashMap();
        Map requestReq = new HashMap();
        Map tcpCont = new HashMap();
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        List qryTagInfo = generateQryTagInfo(isInvalid);

        param.put("OP_CODE", "qryUserDetailInfo_erCiYeWu");
        param.put("UNI_BSS_BODY", uniBssBody);

        uniBssBody.put("REQ", requestReq);

        requestReq.put("TCP_CONT", tcpCont);
        requestReq.put("QRY_TAG_INFOS", qryTagInfo);

        requestReq.put("SERIAL_NUMBER", serialNumber);
        requestReq.put("USER_ID", userId);
        requestReq.put("STAFF_CODE", loginInfo.getStaffInfo().getStaffCode());
        //只查用户中心
        requestReq.put("USER_SOURCE", "2");
        requestReq.put("IS_SELECT_CONTRACT", "0");
        InfServiceHelper.adaptGray(param, requestReq);

        String trans_id = LocalTokenUtil.getDate_yyyyMMddHHmmssSSS() + LocalTokenUtil.randomNum(6);
        tcpCont.put("APP_KEY", "appId");
        tcpCont.put("TRANS_ID", trans_id);

        Map<String, Object> dataMap = new HashMap<>();

        Map result = new HashMap();
        DcPublic cfg = DcPublicCache.get("20112401", "modifySwitch");
        String flag = cfg.getCodea();
        if ("T".equals(flag)) {
            //测试阶段取配置报文返回,后续接口完善后删除
            String rsp = cfg.getCodeb();
            Map<String, Object> orderMap = JSON.parseObject(rsp, Map.class);
            dataMap = (Map<String, Object>) orderMap.get("data");
        } else {
            String resultStr;
            if (KiteStringUtils.isEqual(mode, "http")) {
                resultStr = HttpsCallClient.postStringWithObject(CallClientEnum.QRY_CHANGE_ORIGIN_ORDER, param, null);
            } else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                resultStr = infExchangeService.exchange(new JSONObject(param));
            }
            if (KiteStringUtils.isEmpty(resultStr)) {
                ErrorConsts.INF_INVOKE_ERROR.throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(),
                    "获取变更单信息失败", "获取变更单信息失败");
            }
            result = JSON.parseObject(resultStr, Map.class);
            if (KiteMapUtils.isNotEmpty(result)) {
                String respDesc = KiteMapUtils.getString(result, "status");
                if (KiteStringUtils.isEqual("0", respDesc)) {
                    dataMap = (Map<String, Object>) result.get("data");
                } else {
                    ErrorConsts.INF_INVOKE_ERROR.throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(),
                        "获取变更单信息失败", "获取变更单信息失败");
                }
            } else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(),
                        "获取变更单信息失败", "获取变更单信息失败");
            }
        }

        if (dataMap == null) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(),
                "获取变更单信息失败", "获取变更单信息失败");
        }
        return dataMap;
    }

    private List generateQryTagInfo(boolean isInvalid) {
        List tagInfoList = new ArrayList();
        String tagNames = DcPublicCache.getCodec("20112401", "modifySwitch");
        String[] keys = tagNames.split(",");
        for (int i = 0; i < keys.length; i++) {
            Map tagInfo = new HashMap();
            tagInfo.put("TRANSLATE_FLAG", "1");
            tagInfo.put("VALID_FLAG", "1");
            if (KiteStringUtils.equals(keys[i], "USER")) {
                tagInfo.put("VALID_FLAG", "0");
            }
            if (isInvalid) {
                tagInfo.put("VALID_FLAG", "0");
            }
            tagInfo.put("TAG_NAME", keys[i]);
            tagInfoList.add(tagInfo);
        }
        return tagInfoList;
    }

    //翻译建档渠道
    private String translateInDepart(String inDepartId) {

        String inDepartName = "";

        Map<String, Object> batchQryOrgInfoReq = new HashMap<>();
        batchQryOrgInfoReq.put("PAGE_SIZE", 1);
        batchQryOrgInfoReq.put("PAGE_NUM", 1);
        batchQryOrgInfoReq.put("QRY_TYPE", "1");
        batchQryOrgInfoReq.put("DEPART_IDS", inDepartId);
        batchQryOrgInfoReq.put("STATUS_CD", "0");

        Map<String, Object> uniBssBody = new HashMap<>();
        uniBssBody.put("BATCH_QRY_ORG_INFO_REQ", batchQryOrgInfoReq);

        Map<String, Object> request = new HashMap<>();
        request.put("UNI_BSS_BODY", uniBssBody);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE", "json_chinaUnicom_govEnterprise_operationPlatform_batchQryOrgInfo");
        InfServiceHelper.adaptGray(param, batchQryOrgInfoReq);
        String rsp;
        if (CallClientUtils.callByHttp()) {
            rsp = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            rsp = infExchangeService.exchange(new JSONObject(param));
        }
//        String rsp = HttpsCallClient.postStringWithObject(LocalCallClientEnum.BATCH_QRY_ORG_INFO, LocalTokenUtil.getParamMap(uniBssBody), LocalTokenUtil.getHeaderMap());
        if (KiteStringUtils.isNotEmpty(rsp)) {
            Map result = JSON.parseObject(rsp, Map.class);

            if (KiteMapUtils.isNotEmpty(result)) {
                Map<String, Object> head = (Map<String, Object>) result.get("UNI_BSS_HEAD");
                String respCode = KiteMapUtils.getString(head, "RESP_CODE");
                if (KiteStringUtils.equals(respCode, "00000")) {
                    Map<String, Object> body = (Map<String, Object>) result.get("UNI_BSS_BODY");
                    Map<String, Object> batchQryOrgInfoRsp = (Map<String, Object>) body.get("BATCH_QRY_ORG_INFO_RSP");
                    if (KiteMapUtils.isNotEmpty(batchQryOrgInfoRsp)) {
                        List<Map<String, Object>> dataList = (List<Map<String, Object>>) batchQryOrgInfoRsp.get("DATA_LIST");
                        // 20210624-生产割接的数据-dataList返回为空，添加非空判断
                        if (KiteListUtils.isNotEmpty(dataList)) {
                            Map<String, Object> map = dataList.get(0);
                            if (KiteMapUtils.isNotEmpty(map)) {
                                inDepartName = KiteMapUtils.getString(map, "DEPART_NAME");
                            }
                        }
                    }
                }

            }
        }
        return inDepartName;
    }
}
